package cn.acewill.yxd.yunxundian.ui.sign.Presenter;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.tReportMain;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.MEvaLoadListener;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.MEvaLoadModel;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.MEvaPresenter;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.MEvaluationView;

/**
 * Created by xxx on 2018/1/11.
 * only本地数据
 */

public class MEvaPresenterIml implements MEvaPresenter,MEvaLoadListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private MEvaluationView loadView;
    private MEvaLoadModel loadModel;
    private List<Schedule> dataList;
    private List<Schedule> noScoreList;
    public MEvaPresenterIml(MEvaluationView loadView){
        this.loadView = loadView;
        this.loadModel = new MEvaLoadModelIml();
    }


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0){
                loadView.hideLoadingView();
                if (dataList!=null&&dataList.size()>0){
                    loadView.updateAdapter(dataList);
                }else{
                    loadView.showNoData();
                }
            }
            return false;
        }
    });

    @Override
    public void loadMyData(final String time) { //加载评估项

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    dataList = db.selector(Schedule.class).where("schStartTime", "like", time + "%")
                            .and(WhereBuilder.b("toUserId", "=", MainActivity.id).or("shopmanId", "=", MainActivity.id))
                            .and("states", "in", new int[]{2, 3, 4})
                            .and("title", "!=", "休息")
                            .and("title", "!=", "年假")
                            .and("title", "!=", "其他假")
                            .orderBy("states")
                            .orderBy("schStartTime")
                            .findAll();
                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 加载门店的数据
     * @param shopId shopid
     * @param time 时间
     */
    @Override
    public void loadMyDataByShop(final int shopId,final String time) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(shopId == 0){  //无门店id显示人的数据
                        dataList=db.selector(Schedule.class).where("schStartTime","like",time+"%")
                                .and(WhereBuilder.b("toUserId","=",MainActivity.id).or("shopmanId","=",MainActivity.id))
                                .and("states","in",new int[]{2,3,4})
                                .and("title","!=","休息")
                                .and("title","!=","年假")
                                .and("title","!=","其他假")
                                .orderBy("states")
                                .orderBy("schStartTime")
                                .findAll();
                    }else{
                        dataList = db.selector(Schedule.class).where("toUserId", "=", MainActivity.id)
                                .and("shopID","=",shopId)
                                .and("states", "in", new int[]{1, 2, 3, 4})
                                .and("schStartTime", "like", time + "%")
                                .and("title", "!=", "休息")
                                .and("title", "!=", "年假")
                                .and("title", "!=", "其他假")
                                .orderBy("states")
                                .orderBy("schStartTime")
                                .findAll();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Message msg = new Message();
        msg.what = 0;
        handler.sendMessage(msg);

    }

    @Override
    public void loadScore() {
        String needScedule = getNotScore();
        if (needScedule.equals("null")|| TextUtils.isEmpty(needScedule)){
            return;
        }
        loadModel.loadScoreBySch(needScedule,this);

    }



    @Override
    public void onRequestSuccess(String result) {
        if (result.contains("|")) {
            String[] array = result.split("\\|");
            if (array[0].equals("200")) {
                Gson gson = new Gson();
                Type typeList = new TypeToken<ArrayList<tReportMain>>() {
                }.getType();
                ArrayList<tReportMain> mains = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                updateScor(mains);
                loadView.refreshAdapter();
            }
        }
    }

    @Override
    public void onRequestEro() {
        loadView.requestErro();
        loadView.hideLoadingView();
    }

    //查询不含score的sch
    private String getNotScore(){
        StringBuilder str = new StringBuilder();
        noScoreList = new ArrayList<>();
        if (dataList!=null&&dataList.size()>0){
            for (int i = 0;i<dataList.size();i++){
                Schedule sch = dataList.get(i);
                if (sch.getSubtitle()==null||TextUtils.isEmpty(sch.getSubtitle())){
                    noScoreList.add(sch);
                    str.append(sch.getID()).append(",");
                }
            }
        }
        if (str.length()>0){
            return str.toString().substring(0,str.length()-1);
        }else{
            return "null";
        }
    }

    private  void updateScor(List<tReportMain> mainList){
        if (mainList!=null&& mainList.size()>0){
            for (int k = 0;k<mainList.size();k++){
                // tReportMain main = mainList.get(k);
                if (dataList!=null&&dataList.size()>0){
                    for (int i = 0;i<dataList.size();i++){
                        Schedule sch = dataList.get(i);
                        if (sch.getSubtitle()==null||TextUtils.isEmpty(sch.getSubtitle())){
                            if (mainList.get(k).getSchId() == sch.getID()){
                                sch.setSubtitle(mainList.get(k).getScore()+","+mainList.get(k).getLevel());
                                try {
                                    db.saveOrUpdate(sch);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
